<script setup lang="ts">
  import { computed, onMounted, reactive, ref, watch } from 'vue';
  import { NGrid } from 'naive-ui';
  import JsonEditorVue from 'json-editor-vue3';
  import { useFormRules, useNaiveForm } from '@/hooks/common/form';
  import { fetchGetUserList } from '@/service/api';
  import { $t } from '@/locales';
  import { enableStatusOptions, userGenderOptions } from '@/constants/business';
  import { useCommonStore } from '@/store/modules/common';
  import { formatDate, handleCopy, isPermission } from '@/utils/tools';
  import { useAuthStore } from '@/store/modules/auth';
  import uploadImg from '@/components/common/upload-img.vue';
  import { Api } from '@/typings/api';
  defineOptions({
    name: 'UserOperateDrawer',
  });

  interface Props {
    /** the type of operation */
    operateType: NaiveUI.TableOperateType;
    /** the edit row data */
    rowData?: any;
  }
  const authStore = useAuthStore();
  const h = window.innerHeight * 0.8;

  const props: any = defineProps<Props>();

  interface Emits {
    (e: 'submitted', model: any, type: string): void;
  }

  const emit = defineEmits<Emits>();

  const visible = defineModel<boolean>('visible', {
    default: false,
  });

  const { formRef, validate, restoreValidation } = useNaiveForm();
  const { defaultRequiredRule } = useFormRules();

  const title = computed(() => {
    const titles: Record<NaiveUI.TableOperateType, string> = {
      add: $t('page.systemControl.operationApi.add'),
      edit: $t('page.userData.userList.edit'),
      details: $t('page.manage.role.detailsRole'),
    };
    return titles[props.operateType as NaiveUI.TableOperateType];
  });

  // type Model = Pick<
  //   Api.User.UserListOperate
  // >;
  type Model = any;

  const model: any = reactive(createDefaultModel());

  function createDefaultModel(): Model {
    return {
      avatar:
        'https://tse4-mm.cn.bing.net/th/id/OIP-C.SkDaQXAEpQMMeOZIjf2PVQAAAA?w=207&h=207&c=7&r=0&o=5&dpr=1.3&pid=1.7',
      name: '',
      phone: '',
      role: 'user',
      sex: '0',
      age: '',
      orderId: '',
      email: '',
      address: '',
      text: '',
    };
  }

  type RuleKey = Extract<keyof Model, 'userName' | 'status'>;

  const rules: Record<RuleKey, App.Global.FormRule> = {
    userName: defaultRequiredRule,
    status: defaultRequiredRule,
  };

  /** the enabled role options */
  const roleOptions = ref<CommonType.Option<string>[]>([
    { label: $t('page.common.role.admin'), value: 'admin' },
    { label: $t('page.common.role.user'), value: 'user' },
    // { label: $t('page.common.role.enterprise'), value: 'enterprise' },
  ]);
  const sexOptions = ref<CommonType.Option<string>[]>([
    { label: $t('page.manage.user.gender.female'), value: '0' },
    { label: $t('page.manage.user.gender.male'), value: '1' },
    // { label: $t('page.common.role.enterprise'), value: 'enterprise' },
  ]);

  function handleInitModel() {
    Object.assign(model, createDefaultModel());
    console.log('props.operateType', props.operateType);

    if (props.operateType !== 'add' && props.rowData) {
      Object.assign(model, props.rowData);
      delete model.index;
      delete model.updatedAt;
      delete model.createdAt;
      delete model.deletedAt;
    }
  }

  function closeDrawer() {
    visible.value = false;
  }

  async function handleSubmit() {
    await validate();
    // request
    window.$message?.success($t('common.updateSuccess'));
    closeDrawer();
    emit('submitted', model, props.operateType);
  }

  watch(visible, () => {
    if (visible.value) {
      handleInitModel();
      restoreValidation();
      // getRoleOptions();
    }
  });

  // 图片上传
  const handleUploadImg = (url: string) => {
    model.avatar = url;
  };
</script>

<template>
  <NDrawer
    v-model:show="visible"
    display-directive="show"
    placement="bottom"
    :height="h"
  >
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules" size="small">
        <NGrid v-if="model.id" x-gap="50" y-gap="25" :cols="4">
          <NGi>
            <NFormItem
              :label="$t('page.userData.userList.avatar')"
              path="avatar"
            >
              <NImage width="80" :src="model?.avatar || ''" />
            </NFormItem>
          </NGi>
          <NGi>
            <NFormItem
              :label="$t('page.userData.userList.createdAt')"
              path="createdAt"
            >
              {{
                model.id
                  ? formatDate(props.rowData.createdAt, 'YYYY-MM-DD HH:mm:ss')
                  : ''
              }}
            </NFormItem>
          </NGi>
          <NGi>
            <NFormItem
              :label="$t('page.userData.userList.updatedAt')"
              path="updatedAt"
            >
              {{
                model.id
                  ? formatDate(props.rowData.updatedAt, 'YYYY-MM-DD HH:mm:ss')
                  : ''
              }}
            </NFormItem>
          </NGi>
          <NGi>
            <NFormItem
              :label="$t('page.userData.userList.deletedAt')"
              path="deletedAt"
            >
              {{
                model.id
                  ? formatDate(props.rowData.deletedAt, 'YYYY-MM-DD HH:mm:ss')
                  : ''
              }}
            </NFormItem>
          </NGi>
        </NGrid>
        <NGrid x-gap="50" y-gap="25" :cols="4">
          <NGi v-if="model.id">
            <NFormItem :label="$t('page.userData.userList.id')" path="id">
              {{ model.id }}
              <icon-local-copy
                style="cursor: pointer"
                @click="handleCopy(model.id)"
              />
            </NFormItem>
          </NGi>
          <NGi>
            <NFormItem :label="$t('page.userData.userList.name')" path="name">
              <NInput
                v-model:value="model.name"
                :placeholder="$t('page.userData.userListForm.name')"
                :disabled="!isPermission(authStore.userInfo.role)"
              />
            </NFormItem>
          </NGi>
          <NGi>
            <NFormItem :label="$t('page.userData.userList.phone')" path="phone">
              <NInput
                v-model:value="model.phone"
                :placeholder="$t('page.userData.userListForm.phone')"
                :disabled="!isPermission(authStore.userInfo.role)"
              />
            </NFormItem>
          </NGi>
          <NGi>
            <NFormItem :label="$t('page.userData.userList.role')" path="role">
              <NSelect
                v-model:value="model.role"
                :options="roleOptions"
                :placeholder="$t('page.manage.user.form.userRole')"
                :disabled="!isPermission(authStore.userInfo.role)"
              />
            </NFormItem>
          </NGi>
          <NGi>
            <NFormItem :label="$t('page.manage.user.userGender')" path="sex">
              <NSelect
                v-model:value="model.sex"
                :options="sexOptions"
                :placeholder="$t('page.manage.user.form.userRole')"
                :disabled="!isPermission(authStore.userInfo.sex)"
              />
            </NFormItem>
          </NGi>
          <NGi>
            <NFormItem :label="$t('page.manage.user.age')" path="age">
              <NInput
                v-model:value="model.age"
                :placeholder="$t('page.manage.user.age')"
                :disabled="!isPermission(authStore.userInfo.age)"
              />
            </NFormItem>
          </NGi>
          <NGi>
            <NFormItem :label="$t('page.manage.user.orderId')" path="orderId">
              <NInput
                v-model:value="model.orderId"
                :placeholder="$t('page.manage.user.orderId')"
                :disabled="!isPermission(authStore.userInfo.orderId)"
              />
            </NFormItem>
          </NGi>
          <NGi>
            <NFormItem :label="$t('page.userData.userList.email')" path="email">
              <NInput
                v-model:value="model.email"
                :placeholder="$t('page.userData.userListForm.email')"
                :disabled="!isPermission(authStore.userInfo.role)"
              />
            </NFormItem>
          </NGi>
          <NGi>
            <NFormItem :label="$t('page.manage.user.address')" path="address">
              <NInput
                v-model:value="model.address"
                type="textarea"
                :placeholder="$t('page.manage.user.address')"
                :disabled="!isPermission(authStore.userInfo.address)"
              />
            </NFormItem>
          </NGi>
          <NGi>
            <NFormItem :label="$t('page.manage.user.text')" path="text">
              <NInput
                v-model:value="model.text"
                type="textarea"
                :placeholder="$t('page.manage.user.text')"
                :disabled="!isPermission(authStore.userInfo.text)"
              />
            </NFormItem>
          </NGi>
        </NGrid>

        <!--
 <NFormItem :label="$t('page.manage.user.userGender')" path="userGender">
          <NRadioGroup v-model:value="model.userGender">
            <NRadio v-for="item in userGenderOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
          </NRadioGroup>
        </NFormItem>
-->
      </NForm>
      <template #footer>
        <NSpace :size="32">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{
            $t('common.confirm')
          }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
